import { defineComponent, reactive, ref } from 'vue'
import { userLogin } from '@/http/request/user'
import { ElMessage } from 'element-plus'
import handleErrorMessage from '@/utils/handleErrorMessage'
import { useRouter } from 'vue-router'

export default defineComponent({
  setup () {
    const router = useRouter()

    const form = reactive({
      userName: '',
      password: ''
    })

    const formRef = ref(null)

    const rules = {
      userName: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' }
      ]
    }

    const login = async () => {
      const res = await userLogin(form).then((res) => {
        return res.data
      })
      if (res.errno !== 0) {
        ElMessage.error(handleErrorMessage(res.errno))
        return
      }
      ElMessage.success('登录成功')
      router.push('/')
    }

    return () => {
      return <div>
        <el-form model={form} rules={rules} ref={formRef} label-width="80px">
          <el-form-item label="用户名" prop="userName">
            <el-input v-model={form.userName}></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model={form.password} type="password"></el-input>
          </el-form-item>
        </el-form>
        <div class="form-btn-group">
          <el-button type="primary" onClick={login}>登录</el-button>
        </div>
      </div>
    }
  }
})
